<template>
  <div class="profile-page">
    <el-row :gutter="20">
      <!-- 左侧：头像和基本信息 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="6">
        <el-card class="avatar-card" shadow="hover" v-loading="loading">
          <div class="avatar-section">
            <div class="avatar-wrapper">
              <div class="avatar-preview" @click="openCropDialog">
                <img 
                  v-if="userInfo.avatar" 
                  :src="userInfo.avatar" 
                  class="current-avatar"
                  alt="头像"
                />
                <div v-else class="avatar-placeholder">
                  <el-icon :size="60"><User /></el-icon>
                </div>
                <div class="avatar-overlay">
                  <el-icon><Picture /></el-icon>
                  <span>更换头像</span>
                </div>
              </div>
              <div class="avatar-info">
                <h3 class="nickname">{{ userInfo.nickname || '未设置昵称' }}</h3>
                <p class="username">@{{ userInfo.username || '-' }}</p>
                <p class="user-id">用户ID: {{ userInfo.id || '-' }}</p>
                <p class="roleId">用户权限：{{ 
                  userInfo.roleId === 1 ? '普通用户' : 
                  userInfo.roleId === 2 ? '志愿者' : 
                  userInfo.roleId === 3 ? '管理员' : '-'
                }}</p>

              </div>
            </div>
            
            <div class="user-stats">
              <div class="stat-item">
                <p class="stat-label">手机号：{{ userInfo.phone || '-' }}</p>
                <p class="stat-label">邮箱：{{ userInfo.email || '-' }}</p>
                <p class="stat-label">注册时间：{{ formatTime(userInfo.createTime) || '未知' }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧：编辑表单 -->
      <el-col :xs="24" :sm="24" :md="16" :lg="18">
        <el-card class="form-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="header-title">基本资料</span>
            </div>
          </template>

          <el-form 
            :model="userInfo" 
            :rules="userInfoRules"
            ref="userInfoFormRef"
            label-width="100px"
            class="profile-form"
          >
            <el-form-item label="昵称" prop="nickname">
              <el-input 
                v-model="userInfo.nickname" 
                placeholder="请输入昵称"
                clearable
                maxlength="20"
                show-word-limit
                style="max-width: 400px;"
              />
            </el-form-item>

            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="userInfo.phone" 
                placeholder="请输入手机号"
                clearable
                maxlength="11"
                style="max-width: 400px;"
              />
            </el-form-item>

            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="userInfo.email" 
                placeholder="请输入邮箱"
                clearable
                style="max-width: 400px;"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleSave" :loading="saving">
                <el-icon><Check /></el-icon>
                保存
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 账户安全 -->
        <el-card class="security-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span class="header-title">账户安全</span>
            </div>
          </template>

          <!-- 注销账号 -->
          <div class="account-delete-section">
            <el-alert
              title="危险操作"
              type="error"
              :closable="false"
              show-icon
              class="delete-alert"
            >
              <template #default>
                <p>注销账号后，您的所有数据将被永久删除，此操作不可恢复！</p>
              </template>
            </el-alert>
            <div class="delete-action">
              <el-button 
                type="danger" 
                :icon="Delete"
                @click="handleDeleteAccount"
                :loading="deleting"
              >
                注销账号
              </el-button>
            </div>
          </div>

          <el-form 
            :model="passwordForm" 
            :rules="passwordRules"
            ref="passwordFormRef"
            label-width="100px"
            class="password-form"
          >
            <el-form-item label="当前密码" prop="oldPassword">
              <el-input 
                v-model="passwordForm.oldPassword" 
                type="password" 
                placeholder="请输入当前密码" 
                show-password
                clearable
                style="max-width: 400px;"
              />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input 
                v-model="passwordForm.newPassword" 
                type="password" 
                placeholder="请输入新密码（6-20个字符）" 
                show-password
                clearable
                style="max-width: 400px;"
              />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码" 
                show-password
                clearable
                style="max-width: 400px;"
              />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleChangePassword" :loading="changingPassword">
                <el-icon><Key /></el-icon>
                修改密码
              </el-button>
              <el-button @click="handlePasswordReset">
                <el-icon><Refresh /></el-icon>
                清空
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <!-- 头像裁剪对话框 -->
    <el-dialog 
      v-model="cropDialogVisible" 
      title="选择头像" 
      width="600px"
      @close="closeCropDialog"
    >
      <div class="crop-container">
        <!-- 文件选择 -->
        <div v-if="!selectedImage" class="upload-area">
          <el-upload
            class="image-uploader"
            :show-file-list="false"
            :before-upload="handleImageSelect"
            accept="image/*"
          >
            <div class="upload-box">
              <el-icon :size="48"><Plus /></el-icon>
              <p>点击或拖拽图片到此处</p>
              <p class="upload-tip">支持 JPG、PNG 格式，建议尺寸不小于 200x200</p>
            </div>
          </el-upload>
        </div>

        <!-- 图片裁剪区域 -->
        <div v-else class="crop-area">
          <div class="crop-preview-wrapper">
            <div class="crop-image-container" ref="cropContainerRef">
              <img 
                ref="cropImageRef"
                :src="selectedImage" 
                class="crop-source-image"
                @load="initCrop"
              />
              <div 
                v-if="showCropBox"
                class="crop-box"
                :style="cropBoxStyle"
                @mousedown="startDrag"
              >
                <div class="crop-box-handle" v-for="(handle, index) in cropHandles" :key="index"
                  :class="`handle-${handle.position}`"
                  :style="getHandleStyle(handle)"
                  @mousedown.stop="startResize(index, $event)"
                ></div>
              </div>
            </div>
          </div>
          
          <!-- 预览区域 -->
          <div class="preview-area">
            <div class="preview-title">预览</div>
            <div class="preview-circles">
              <div class="preview-circle large">
                <img v-if="croppedImage" :src="croppedImage" alt="预览" />
              </div>
              <div class="preview-circle medium">
                <img v-if="croppedImage" :src="croppedImage" alt="预览" />
              </div>
              <div class="preview-circle small">
                <img v-if="croppedImage" :src="croppedImage" alt="预览" />
              </div>
            </div>
            <div class="preview-sizes">
              <span>100x100</span>
              <span>80x80</span>
              <span>50x50</span>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCropDialog">取消</el-button>
          <el-button v-if="selectedImage && !croppedImage" @click="handleCrop">确认裁剪</el-button>
          <el-button v-if="croppedImage" type="primary" @click="handleUploadCroppedImage" :loading="uploading">
            <el-icon><Upload /></el-icon>
            上传头像
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
import { 
  Plus, User, Lock, Check, Refresh, Key, Edit, Upload, Picture, Delete
} from '@element-plus/icons-vue';

export default {
  name: 'Profile',
  components: {
    Plus,
    User,
    Lock,
    Check,
    Refresh,
    Key,
    Edit,
    Upload,
    Picture,
    Delete
  },
  data() {
    // 手机号验证
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入手机号'));
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
      } else {
        callback();
      }
    };

    // 邮箱验证
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入邮箱'));
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
        callback(new Error('请输入正确的邮箱地址'));
      } else {
        callback();
      }
    };

    // 确认密码验证
    const validateConfirmPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请再次输入新密码'));
      } else if (value !== this.passwordForm.newPassword) {
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    };

    return {
      loading: false,
      saving: false,
      changingPassword: false,
      uploading: false,
      deleting: false,
      originalUserInfo: {},
      cropDialogVisible: false,
      selectedImage: null,
      showCropBox: false,
      croppedImage: null,
      cropBoxStyle: {
        left: '50px',
        top: '50px',
        width: '200px',
        height: '200px'
      },
      cropHandles: [
        { position: 'nw' },
        { position: 'ne' },
        { position: 'sw' },
        { position: 'se' },
        { position: 'n' },
        { position: 's' },
        { position: 'e' },
        { position: 'w' }
      ],
      isDragging: false,
      isResizing: false,
      dragStart: { x: 0, y: 0 },
      resizeStart: { x: 0, y: 0, width: 0, height: 0 },
      resizeHandle: null,

      userInfo: {
        id: null,
        nickname: '',
        phone: '',
        email: '',
        avatar: '',
        createTime: ''
      },
      
      passwordForm: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },

      userInfoRules: {
        nickname: [
          { 
            validator: (rule, value, callback) => {
              if (!value || value.trim() === '') {
                callback(); // 允许为空
              } else if (value.length < 2 || value.length > 20) {
                callback(new Error('昵称长度在 2 到 20 个字符'));
              } else {
                callback();
              }
            }, 
            trigger: 'blur' 
          }
        ],
        phone: [
          { required: false, validator: (rule, value, callback) => {
            if (!value || value.trim() === '') {
              callback(); // 允许为空
            } else if (!/^1[3-9]\d{9}$/.test(value)) {
              callback(new Error('请输入正确的手机号码'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
        ],
        email: [
          { required: false, validator: (rule, value, callback) => {
            if (!value || value.trim() === '') {
              callback(); // 允许为空
            } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
              callback(new Error('请输入正确的邮箱地址'));
            } else {
              callback();
            }
          }, trigger: 'blur' }
        ]
      },

      passwordRules: {
        oldPassword: [
          { required: true, message: '请输入当前密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validateConfirmPassword, trigger: 'blur' }
        ]
      }
    };
  },
  async mounted() {
    await this.loadUserInfo();
  },
  methods: {
    // 加载用户信息
    async loadUserInfo() {
      this.loading = true;
      const userId = localStorage.getItem('userId');
      
      if (!userId) {
        ElMessage.error('用户未登录');
        this.loading = false;
        return;
      }

      try {
        const res = await axios.get(`http://localhost:8080/api/user/${userId}`);
        if (res.data.code === 200) {
          this.userInfo = { ...res.data.data };
          // 如果是相对路径，转换为完整URL
          if (this.userInfo.avatar && this.userInfo.avatar.startsWith('/') && !this.userInfo.avatar.startsWith('http')) {
            this.userInfo.avatar = `http://localhost:8080${this.userInfo.avatar}`;
          }
          this.originalUserInfo = JSON.parse(JSON.stringify(res.data.data));
        } else {
          ElMessage.error(res.data.msg || '加载用户信息失败');
        }
      } catch (error) {
        ElMessage.error('加载用户信息失败：' + (error.message || '网络错误'));
      } finally {
        this.loading = false;
      }
    },
    
    // 打开裁剪对话框
    openCropDialog() {
      this.cropDialogVisible = true;
      this.selectedImage = null;
      this.croppedImage = null;
      this.showCropBox = false;
    },
    
    // 关闭裁剪对话框
    closeCropDialog() {
      this.cropDialogVisible = false;
      this.selectedImage = null;
      this.croppedImage = null;
      this.showCropBox = false;
    },
    
    // 选择图片
    handleImageSelect(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.selectedImage = e.target.result;
        this.$nextTick(() => {
          this.initCrop();
        });
      };
      reader.readAsDataURL(file);
      return false; // 阻止自动上传
    },
    
    // 初始化裁剪框
    initCrop() {
      if (!this.$refs.cropImageRef || !this.$refs.cropContainerRef) return;
      
      const img = this.$refs.cropImageRef;
      const container = this.$refs.cropContainerRef;
      
      // 确保图片加载完成
      if (img.complete) {
        this.setupCropBox(img, container);
      } else {
        img.onload = () => {
          this.setupCropBox(img, container);
        };
      }
    },
    
    // 设置裁剪框
    setupCropBox(img, container) {
      const imgWidth = img.offsetWidth;
      const imgHeight = img.offsetHeight;
      const containerWidth = container.offsetWidth;
      
      // 设置裁剪框初始大小和位置（200x200，居中）
      const cropSize = Math.min(200, imgWidth, imgHeight);
      const left = (containerWidth - cropSize) / 2;
      const top = (imgHeight - cropSize) / 2;
      
      this.cropBoxStyle = {
        left: `${left}px`,
        top: `${top}px`,
        width: `${cropSize}px`,
        height: `${cropSize}px`
      };
      
      this.showCropBox = true;
    },
    
    // 获取手柄样式
    getHandleStyle(handle) {
      const positions = {
        nw: { top: '-4px', left: '-4px', cursor: 'nw-resize' },
        ne: { top: '-4px', right: '-4px', cursor: 'ne-resize' },
        sw: { bottom: '-4px', left: '-4px', cursor: 'sw-resize' },
        se: { bottom: '-4px', right: '-4px', cursor: 'se-resize' },
        n: { top: '-4px', left: '50%', transform: 'translateX(-50%)', cursor: 'n-resize' },
        s: { bottom: '-4px', left: '50%', transform: 'translateX(-50%)', cursor: 's-resize' },
        e: { top: '50%', right: '-4px', transform: 'translateY(-50%)', cursor: 'e-resize' },
        w: { top: '50%', left: '-4px', transform: 'translateY(-50%)', cursor: 'w-resize' }
      };
      return positions[handle.position] || {};
    },
    
    // 开始拖拽
    startDrag(e) {
      this.isDragging = true;
      const rect = this.$refs.cropContainerRef.getBoundingClientRect();
      this.dragStart = {
        x: e.clientX - rect.left - parseInt(this.cropBoxStyle.left),
        y: e.clientY - rect.top - parseInt(this.cropBoxStyle.top)
      };
      document.addEventListener('mousemove', this.onDrag);
      document.addEventListener('mouseup', this.stopDrag);
    },
    
    // 拖拽中
    onDrag(e) {
      if (!this.isDragging) return;
      
      const rect = this.$refs.cropContainerRef.getBoundingClientRect();
      const img = this.$refs.cropImageRef;
      
      let x = e.clientX - rect.left - this.dragStart.x;
      let y = e.clientY - rect.top - this.dragStart.y;
      
      // 限制在图片范围内
      const maxX = img.offsetWidth - parseInt(this.cropBoxStyle.width);
      const maxY = img.offsetHeight - parseInt(this.cropBoxStyle.height);
      
      x = Math.max(0, Math.min(x, maxX));
      y = Math.max(0, Math.min(y, maxY));
      
      this.cropBoxStyle.left = `${x}px`;
      this.cropBoxStyle.top = `${y}px`;
    },
    
    // 停止拖拽
    stopDrag() {
      this.isDragging = false;
      document.removeEventListener('mousemove', this.onDrag);
      document.removeEventListener('mouseup', this.stopDrag);
    },
    
    // 开始调整大小
    startResize(handleIndex, e) {
      this.isResizing = true;
      this.resizeHandle = handleIndex;
      const rect = this.$refs.cropContainerRef.getBoundingClientRect();
      this.resizeStart = {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top,
        width: parseInt(this.cropBoxStyle.width),
        height: parseInt(this.cropBoxStyle.height),
        left: parseInt(this.cropBoxStyle.left),
        top: parseInt(this.cropBoxStyle.top)
      };
      document.addEventListener('mousemove', this.onResize);
      document.addEventListener('mouseup', this.stopResize);
      e.stopPropagation();
    },
    
    // 调整大小中
    onResize(e) {
      if (!this.isResizing) return;
      
      const rect = this.$refs.cropContainerRef.getBoundingClientRect();
      const img = this.$refs.cropImageRef;
      const handle = this.cropHandles[this.resizeHandle];
      
      let x = e.clientX - rect.left;
      let y = e.clientY - rect.top;
      
      let newLeft = this.resizeStart.left;
      let newTop = this.resizeStart.top;
      let newWidth = this.resizeStart.width;
      let newHeight = this.resizeStart.height;
      
      const minSize = 50;
      
      if (handle.position.includes('e')) {
        newWidth = Math.max(minSize, x - this.resizeStart.left);
        newWidth = Math.min(newWidth, img.offsetWidth - newLeft);
      }
      if (handle.position.includes('w')) {
        const deltaX = this.resizeStart.left - x;
        newLeft = Math.max(0, this.resizeStart.left - deltaX);
        newWidth = Math.max(minSize, this.resizeStart.width + deltaX);
        if (newLeft + newWidth > img.offsetWidth) {
          newWidth = img.offsetWidth - newLeft;
        }
      }
      if (handle.position.includes('s')) {
        newHeight = Math.max(minSize, y - this.resizeStart.top);
        newHeight = Math.min(newHeight, img.offsetHeight - newTop);
      }
      if (handle.position.includes('n')) {
        const deltaY = this.resizeStart.top - y;
        newTop = Math.max(0, this.resizeStart.top - deltaY);
        newHeight = Math.max(minSize, this.resizeStart.height + deltaY);
        if (newTop + newHeight > img.offsetHeight) {
          newHeight = img.offsetHeight - newTop;
        }
      }
      
      // 保持正方形
      const size = Math.min(newWidth, newHeight);
      this.cropBoxStyle.width = `${size}px`;
      this.cropBoxStyle.height = `${size}px`;
      this.cropBoxStyle.left = `${newLeft}px`;
      this.cropBoxStyle.top = `${newTop}px`;
    },
    
    // 停止调整大小
    stopResize() {
      this.isResizing = false;
      this.resizeHandle = null;
      document.removeEventListener('mousemove', this.onResize);
      document.removeEventListener('mouseup', this.stopResize);
    },
    
    // 执行裁剪
    handleCrop() {
      if (!this.$refs.cropImageRef) return;
      
      const img = this.$refs.cropImageRef;
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      
      const cropX = parseInt(this.cropBoxStyle.left);
      const cropY = parseInt(this.cropBoxStyle.top);
      const cropSize = parseInt(this.cropBoxStyle.width);
      
      // 计算实际裁剪尺寸（考虑图片实际尺寸）
      const scaleX = img.naturalWidth / img.offsetWidth;
      const scaleY = img.naturalHeight / img.offsetHeight;
      
      canvas.width = cropSize;
      canvas.height = cropSize;
      
      ctx.drawImage(
        img,
        cropX * scaleX, cropY * scaleY, cropSize * scaleX, cropSize * scaleY,
        0, 0, cropSize, cropSize
      );
      
      this.croppedImage = canvas.toDataURL('image/png');
    },
    
    // 上传裁剪后的图片
    async handleUploadCroppedImage() {
      if (!this.croppedImage || !this.userInfo.id) {
        ElMessage.error('请先选择并裁剪图片');
        return;
      }
      
      this.uploading = true;
      
      try {
        // 将 base64 转换为 Blob
        const blob = await this.dataURLtoBlob(this.croppedImage);
        const formData = new FormData();
        formData.append('file', blob, 'avatar.png');
        formData.append('userId', this.userInfo.id);
        
        const res = await axios.post('http://localhost:8080/api/user/uploadAvatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        console.log('上传响应完整数据:', res);
        console.log('res.data:', res.data);
        console.log('响应类型:', typeof res.data);
        if (res.data && typeof res.data === 'object') {
          console.log('响应键:', Object.keys(res.data));
        }
        
        let avatarUrl = '';
        
        // 后端返回格式: { code: 200, msg: "上传成功", avatar: "/uploads/avatars/xxx.jpg" }
        // 尝试多种可能的响应格式
        if (!res.data) {
          console.warn('响应数据为空');
        } else if (res.data.avatar) {
          // 情况1: 直接有 avatar 字段（最优先）
          avatarUrl = res.data.avatar;
        } else if (res.data.data) {
          // 情况2: 包装在 data 字段中
          if (res.data.data.avatar) {
            avatarUrl = res.data.data.avatar;
          } else if (typeof res.data.data === 'string') {
            avatarUrl = res.data.data;
          } else if (res.data.data.url) {
            avatarUrl = res.data.data.url;
          }
        } else if (typeof res.data === 'string') {
          // 情况3: 响应本身就是字符串
          avatarUrl = res.data;
        } else if (res.data.url) {
          // 情况4: 有 url 字段
          avatarUrl = res.data.url;
        }
        
        console.log('提取的 avatarUrl:', avatarUrl);
        
        if (avatarUrl && avatarUrl.trim()) {
          // 如果是相对路径，添加完整域名
          if (avatarUrl.startsWith('/') && !avatarUrl.startsWith('http')) {
            avatarUrl = `http://localhost:8080${avatarUrl}`;
          }
          this.userInfo.avatar = avatarUrl;
          console.log('最终头像URL:', avatarUrl);
          // 直接保存头像，不触发表单验证
          await this.saveAvatarOnly(avatarUrl);
          ElMessage.success('头像上传成功');
          this.closeCropDialog();
        } else {
          console.error('无法获取头像URL，完整响应:', JSON.stringify(res.data, null, 2));
          ElMessage.error('上传失败：无法获取头像URL，请查看控制台了解详细信息');
        }
      } catch (error) {
        console.error('上传失败:', error);
        ElMessage.error('上传失败：' + (error.response?.data?.msg || error.message || '网络错误'));
      } finally {
        this.uploading = false;
      }
    },
    
    // Base64 转 Blob
    dataURLtoBlob(dataURL) {
      return new Promise((resolve) => {
        const arr = dataURL.split(',');
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        resolve(new Blob([u8arr], { type: mime }));
      });
    },
    
    // 只保存头像，不触发表单验证
    async saveAvatarOnly(avatarUrl) {
      try {
        const payload = {
          id: this.userInfo.id,
          avatar: avatarUrl,
          nickname: this.userInfo.nickname,
          phone: this.userInfo.phone,
          email: this.userInfo.email
        };
        
        const res = await axios.put('http://localhost:8080/api/user/update', payload);
        
        if (res.data.code === 200) {
          this.originalUserInfo = JSON.parse(JSON.stringify(this.userInfo));
        }
      } catch (error) {
        console.error('保存头像失败:', error);
      }
    },
    
    // 保存修改
    async handleSave() {
      if (!this.$refs.userInfoFormRef) return;

      // 只验证有值的字段
      await this.$refs.userInfoFormRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请检查表单信息');
          return;
        }

        // 只发送有变化的字段
        const payload = {
          id: this.userInfo.id
        };

        // 只添加与原始值不同的字段（包括空值）
        if (this.userInfo.nickname !== this.originalUserInfo.nickname) {
          payload.nickname = this.userInfo.nickname || '';
        }
        if (this.userInfo.phone !== this.originalUserInfo.phone) {
          payload.phone = this.userInfo.phone || '';
        }
        if (this.userInfo.email !== this.originalUserInfo.email) {
          payload.email = this.userInfo.email || '';
        }

        // 如果头像已更新，添加到payload
        if (this.userInfo.avatar && this.userInfo.avatar !== this.originalUserInfo.avatar) {
          payload.avatar = this.userInfo.avatar;
        }

        // 检查是否有任何修改
        if (Object.keys(payload).length === 1) {
          ElMessage.info('没有需要保存的修改');
          return;
        }

        this.saving = true;
        try {
          const res = await axios.put('http://localhost:8080/api/user/update', payload);
          
          if (res.data.code === 200) {
            ElMessage.success('保存成功');
            // 重新加载用户信息以获取最新数据
            await this.loadUserInfo();
            if (this.userInfo.nickname) {
              localStorage.setItem('username', this.userInfo.nickname);
            }
          } else {
            ElMessage.error(res.data.msg || '保存失败');
          }
        } catch (error) {
          ElMessage.error('保存失败：' + (error.message || '网络错误'));
        } finally {
          this.saving = false;
        }
      });
    },
    
    // 重置个人信息
    handleReset() {
      this.userInfo = JSON.parse(JSON.stringify(this.originalUserInfo));
      if (this.userInfo.avatar && this.userInfo.avatar.startsWith('/') && !this.userInfo.avatar.startsWith('http')) {
        this.userInfo.avatar = `http://localhost:8080${this.userInfo.avatar}`;
      }
      this.$refs.userInfoFormRef?.clearValidate();
      ElMessage.info('已重置为原始数据');
    },
    
    // 修改密码
    async handleChangePassword() {
      if (!this.$refs.passwordFormRef) return;

      await this.$refs.passwordFormRef.validate(async (valid) => {
        if (!valid) {
          ElMessage.warning('请完善密码信息');
          return;
        }

        this.changingPassword = true;
        try {
          const payload = {
            id: this.userInfo.id,
            oldPassword: this.passwordForm.oldPassword,
            newPassword: this.passwordForm.newPassword
          };

          const res = await axios.put('http://localhost:8080/api/user/update', payload);
          
          if (res.data.code === 200) {
            ElMessage.success('密码修改成功，请重新登录');
            this.handlePasswordReset();
            setTimeout(() => {
              localStorage.clear();
              this.$router.push('/login');
            }, 1500);
          } else {
            ElMessage.error(res.data.msg || '密码修改失败');
          }
        } catch (error) {
          ElMessage.error('密码修改失败：' + (error.message || '网络错误'));
        } finally {
          this.changingPassword = false;
        }
      });
    },

    // 清空密码表单
    handlePasswordReset() {
      this.passwordForm = {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
      this.$refs.passwordFormRef?.clearValidate();
    },

    // 注销账号
    async handleDeleteAccount() {
      // 先要求输入密码确认
      await ElMessageBox.prompt(
        '请输入您的密码以确认注销账号',
        '注销账号确认',
        {
          confirmButtonText: '确认注销',
          cancelButtonText: '取消',
          inputType: 'password',
          inputPlaceholder: '请输入密码',
          inputValidator: (value) => {
            if (!value) {
              return '请输入密码';
            }
            return true;
          },
          dangerouslyUseHTMLString: false,
          type: 'warning'
        }
      )
      .then(async ({ value: password }) => {
        // 二次确认
        await ElMessageBox.confirm(
          '注销账号后，您的所有数据将被永久删除，此操作不可恢复！\n\n确定要注销账号吗？',
          '最后确认',
          {
            confirmButtonText: '确定注销',
            cancelButtonText: '取消',
            type: 'error',
            dangerouslyUseHTMLString: false
          }
        );

        this.deleting = true;
        try {
          const userId = localStorage.getItem('userId');
          if (!userId) {
            ElMessage.error('用户未登录');
            return;
          }

          // 根据后端接口：@DeleteMapping("/selfdelete")，使用 DELETE 方法，URL 参数
          try {
            const res = await axios.delete('http://localhost:8080/api/user/selfdelete', {
              params: {
                userId: userId,
                password: password
              }
            });

            if (res.data.code === 200) {
              ElMessage.success(res.data.msg || '账号已注销成功');
              // 清除所有本地存储
              localStorage.clear();
              // 跳转到登录页
              setTimeout(() => {
                this.$router.push('/login');
              }, 1500);
            } else {
              ElMessage.error(res.data.msg || '注销失败');
            }
          } catch (error) {
            console.error('注销账号失败:', error);
            if (error.response?.data?.msg) {
              ElMessage.error(error.response.data.msg);
            } else {
              ElMessage.error('注销失败：' + (error.message || '网络错误'));
            }
          }
        } catch (error) {
          if (error === 'cancel') {
            // 用户取消
            return;
          }
          console.error('注销账号失败:', error);
          ElMessage.error('注销失败：' + (error.message || '网络错误'));
        } finally {
          this.deleting = false;
        }
      })
      .catch(() => {
        // 用户取消输入密码或确认
      });
    },

    // 时间格式化
    formatTime(time) {
      if (!time) return '未知';
      
      if (typeof time === 'string') {
        const date = new Date(time);
        if (isNaN(date.getTime())) {
          return time;
        }
        time = date;
      }
      
      if (time instanceof Date) {
        const year = time.getFullYear();
        const month = String(time.getMonth() + 1).padStart(2, '0');
        const day = String(time.getDate()).padStart(2, '0');
        const hours = String(time.getHours()).padStart(2, '0');
        const minutes = String(time.getMinutes()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      }
      
      return time;
    }
  }
};
</script>

<style scoped>
.profile-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100%;
}

/* 头像卡片 */
.avatar-card {
  border-radius: 8px;
  margin-bottom: 20px;
  height: 100%;
}

.avatar-card :deep(.el-card__body) {
  padding: 24px;
}

.avatar-section {
  text-align: center;
}

.avatar-wrapper {
  margin-bottom: 24px;
}

.avatar-preview {
  position: relative;
  width: 120px;
  height: 120px;
  margin: 0 auto 16px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #e4e7ed;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fafafa;
}

.avatar-preview:hover {
  border-color: #909399;
}

.avatar-preview:hover .avatar-overlay {
  opacity: 1;
}

.current-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  color: #909399;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  opacity: 0;
  transition: opacity 0.3s ease;
  font-size: 12px;
}

.avatar-overlay .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

.avatar-info {
  margin-bottom: 24px;
}

.nickname {
  margin: 0 0 8px 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.user-id {
  margin: 0;
  font-size: 14px;
  color: #909399;
}

.user-stats {
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.stat-item {
  margin-bottom: 16px;
}

.stat-item:last-child {
  margin-bottom: 0;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

/* 表单卡片 */
.form-card,
.security-card {
  border-radius: 8px;
  margin-bottom: 20px;
}

.security-card {
  margin-bottom: 0;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.profile-form,
.password-form {
  padding: 8px 0;
}

/* 注销账号区域 */
.account-delete-section {
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.delete-alert {
  margin-bottom: 20px;
  border-radius: 8px;
}

.delete-alert :deep(.el-alert__content) {
  line-height: 1.8;
}

.delete-alert p {
  margin: 0;
  color: #606266;
}

.delete-action {
  display: flex;
  justify-content: flex-start;
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-button) {
  border-radius: 4px;
}

/* 裁剪对话框样式 */
.crop-container {
  min-height: 400px;
}

.upload-area {
  padding: 40px 20px;
  text-align: center;
}

.image-uploader {
  width: 100%;
}

.upload-box {
  padding: 60px 20px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  color: #909399;
}

.upload-box:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.upload-box p {
  margin: 12px 0 0 0;
  font-size: 14px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
}

.crop-area {
  display: flex;
  gap: 24px;
}

.crop-preview-wrapper {
  flex: 1;
  max-width: 400px;
}

.crop-image-container {
  position: relative;
  width: 100%;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  background: #fafafa;
}

.crop-source-image {
  width: 100%;
  height: auto;
  display: block;
  max-height: 400px;
  object-fit: contain;
}

.crop-box {
  position: absolute;
  border: 2px solid #409eff;
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
  cursor: move;
  background: transparent;
}

.crop-box-handle {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #409eff;
  border: 2px solid white;
  border-radius: 50%;
}

.preview-area {
  flex: 0 0 200px;
}

.preview-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.preview-circles {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 12px;
}

.preview-circle {
  border-radius: 50%;
  overflow: hidden;
  border: 2px solid #e4e7ed;
  background: #fafafa;
  margin: 0 auto;
}

.preview-circle.large {
  width: 100px;
  height: 100px;
}

.preview-circle.medium {
  width: 80px;
  height: 80px;
}

.preview-circle.small {
  width: 50px;
  height: 50px;
}

.preview-circle img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-sizes {
  display: flex;
  justify-content: space-around;
  font-size: 12px;
  color: #909399;
}

/* 响应式 */
@media (max-width: 992px) {
  .avatar-card {
    margin-bottom: 20px;
  }
  
  .crop-area {
    flex-direction: column;
  }
  
  .preview-area {
    flex: 1;
  }
  
  .preview-circles {
    flex-direction: row;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .profile-page {
    padding: 12px;
  }
  
  .avatar-card :deep(.el-card__body) {
    padding: 20px;
  }
}
</style>
